import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import jwtdecode from "jwt-decode";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Login

  },
  {
    path: '/home',
    component: () => import('../components/Home.vue'),
    redirect: '/reports',
    children: [
      {
        path: '/users',
        component: () => import('../components/Users.vue')
      },
      {
        path: '/roles',
        component: () => import('../components/Roles.vue')
      },
      {
        path: '/rights',
        component: () => import('../components/Rights.vue')
      },
      {
        path: '/goods',
        component: () => import('../components/Goods.vue')
      },
      {
        path: '/goodsAdd',
        component: () => import('../components/GoodsAdd.vue'),
        meta: { parentPath: '/goods' }
      },
      {
        path: '/params',
        component: () => import('../components/Params.vue')
      },
      {
        path: '/categories',
        component: () => import('../components/Categories.vue')
      },
      {
        path: '/orders',
        component: () => import('../components/Orders.vue')
      },
      {
        path: '/reports',
        component: () => import('../components/Reports.vue')
      },
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 判断是否是登陆页面  登陆页面放行
  if (to.path === '/') {
    next()
  }
  // 非登陆页面判断是否有token
  if (to.path !== '/') {
    let token = sessionStorage.getItem('token')
    if (!token) {
      next('/')
    } else {
      // 有token还得判断是否过期
      let { exp } = jwtdecode(token)
      let time = new Date().getTime()
      time = Math.floor(time / 1000)
      if (exp - time >= 0) {
        next()
      } else {
        next('/')
      }
    }
  }
})

export default router
